package com.bawei.mall.pay.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import com.bawei.mall.pay.service.IPayService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * @Author：HaoYunde
 * @Package：com.bawei.mall.pay.service.impl
 * @Project：mall_cloud
 * @name：AliPayServiceImpl
 * @Date：2024/7/11 14:10
 */
@Service
public class AliPayServiceImpl implements IPayService {
    @Value("${alipay.client.serverUrl}")
    private String serverUrl;
    @Value("${alipay.client.appId}")
    private String appId;
    @Value("${alipay.client.privateKey}")
    private String privateKey;
    @Value("${alipay.client.format}")
    private String format;
    @Value("${alipay.client.charset}")
    private String charset;
    @Value("${alipay.client.signType}")
    private String signType;
    @Value("${alipay.client.alipayPublicKey}")
    private String alipayPublicKey;


    @Override
    public String webPay(Long orderId, Integer payType) {
        AlipayClient alipayClient = new DefaultAlipayClient(
                serverUrl,
                appId,
                privateKey,
                format,
                charset,
                alipayPublicKey,
                signType
        );

        AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
        request.setNotifyUrl("");// 异步接收地址
        request.setReturnUrl("https://www.macrozheng.com/app/#/");// 同步跳转地址

        // 必传参数
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", "20210817010101004"); // 商户订单号
        bizContent.put("total_amount", 0.01); // 支付金额
        bizContent.put("subject", "测试商品"); // 订单标题

        // 可选参数
        bizContent.put("product_code", "QUICK_WAP_WAY"); // 手机网站支付默认传值QUICK_WAP_WAY

        request.setBizContent(bizContent.toString());

        AlipayTradeWapPayResponse response = null;
        try {
            response = alipayClient.pageExecute(request, "POST");
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
        String body = response.getBody();

        if (response.isSuccess()) {
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
        return body;
    }
}
